<?php

namespace Modules\Admin\Http\Middleware;

use Closure;
use Modules\Admin\Services\Log\OperationLogService;
use Modules\Common\Exceptions\ApiException;
use Illuminate\Http\Request;
use Modules\Common\Exceptions\MessageData;
use Modules\Common\Exceptions\StatusData;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use JWTAuth;

class AdminApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        \Config::set('auth.defaults.guard', 'auth_admin');
        \Config::set('jwt.ttl', config('admin.jwt_ttl'));
        $route_data = $request->route();
        //$url = str_replace($route_data->getAction()['prefix'] . '/',"",$route_data->uri);
        $url = str_replace( 'api/v1/',"",$route_data->uri);
        $url_arr = ['admin/common/login','admin/common/refreshToken','admin/common/getConfigInfo','admin/common/getCode'];
        $api_key = $request->header('apikey');
        if($api_key != config('admin.api_key')){
            throw new ApiException(['status'=>StatusData::TOKEN_ERROR_KEY,'message'=>MessageData::TOKEN_ERROR_KEY]);
            return $next();
        }
        if(in_array($url,$url_arr)){
            return $next($request);
        }
        try {
            if (! $adminInfo = JWTAuth::parseToken()->authenticate()) {  //获取到用户数据，并赋值给$user   'msg' => '用户不存在'
                throw new ApiException(['status'=>StatusData::TOKEN_ERROR_SET,'message'=>MessageData::TOKEN_ERROR_SET]);
                return $next();
            }

        }catch (TokenBlacklistedException $e) {
            // 这个时候是老的token被拉到黑名单了
            throw new ApiException(['status'=>StatusData::TOKEN_ERROR_BLACK,'message'=>MessageData::TOKEN_ERROR_BLACK]);
            return $next();
        } catch (TokenExpiredException $e) {
            //token已过期
            throw new ApiException(['status'=>StatusData::TOKEN_ERROR_EXPIRED,'message'=>MessageData::TOKEN_ERROR_EXPIRED]);
            return $next();
        } catch (TokenInvalidException $e) {
            //token无效
            throw new ApiException(['status'=>StatusData::TOKEN_ERROR_JWT,'message'=>MessageData::TOKEN_ERROR_JWT]);
            return $next();
        } catch (JWTException $e) {
            //'缺少token'
            throw new ApiException(['status'=>StatusData::TOKEN_ERROR_JTB,'message'=>MessageData::TOKEN_ERROR_JTB]);
            return $next();
        }
        if(in_array($url,['admin/common/my'])){
            return $next($request);
        }
        // 写入日志并判断是否有权限
        $res = (new OperationLogService())->store($adminInfo,$url);
        if($res == 3){
            throw new ApiException(['status'=>StatusData::ERROR_NO_PERMISSION,'message'=>MessageData::ERROR_NO_PERMISSION]);
            return $next();
        };
        if($res == 2){
            throw new ApiException(['status'=>StatusData::BAD_REQUEST,'message'=>'测试站无操作权限，可联系项目管理员进行体验']);
            return $next();
        };
        return $next($request);
    }
}
